from dcatalyst import ChainError
from django.conf.urls.defaults import url, patterns
import inspect

def include_url_pattern(view):    
    if type(view) is str:
        raise ChainError("View '%s' is not a function! " 
                         + "Specifying other types (like a string path) is not supported yet." % (str(view)))
    if not view.__dict__.has_key('_capture_path'):
        raise ChainError('View %s is not a chained view!' % (view.__name__))
    
    capture_path = view._capture_path
    if capture_path[-1:] == '/': # eliminate trailing slash
        capture_path = capture_path[0:-1]
    capture_path = r'^%s/$' % (capture_path)

    return url(capture_path, view)

def chained_patterns(prefix, *args):
    pattern_list = []
    for t in args:
        if not inspect.isroutine(t):
            raise ChainError("View '%s' is not a function! " 
                             + "Specifying other types (like a string path) is not supported yet." % (str(t)))
        t = include_url_pattern(t)
        t.add_prefix(prefix)
        pattern_list.append(t)
    return pattern_list
